using System;
using System.Web.Security;
using System.Web;
namespace Symbonix.NorSoNet.Security.BLL.Membership {
	
	public class UserFactory : IUserFactory  {
		
		public IUser GetUser(int id) {
            return GetSpecificUser(SystemUser.GetInstance().Load(id));
		}
		
		public IUser GetUser() {
            return SystemUser.GetInstance();
		}

        public IUser GetUser(string role)
        {
            if (role == Options.UserRoles.Member.ToString())
                return Member.GetInstance();
            else if (role == Options.UserRoles.Admin.ToString())
                return Admin.GetInstance();
            else
                return null;
        }
		
		public IUser GetCurrentUser() {
            return GetSpecificUser(SystemUser.GetInstance().GetUserByUserName(HttpContext.Current.User.Identity.Name));
		}

        /// <summary>
        /// For internal use, creates a role specific user instance froma a generic user instance
        /// (SysmteUser to Admin or Member)
        /// [Jalal]
        /// </summary>
        /// <param name="user">Generic user instance</param>
        /// <returns>Sepecific user instance</returns>
        private IUser GetSpecificUser(IUser user)
        {
            string[] userRoles = Roles.Provider.GetRolesForUser(user.UserName);
            Options.UserRoles userRole = Options.UserRoles.None;

            foreach (string role in userRoles)
            {
                if (role == Options.UserRoles.Member.ToString())
                    userRole = Options.UserRoles.Member;
                else if (role == Options.UserRoles.Admin.ToString())
                    userRole = Options.UserRoles.Admin;
            }
            if (userRole == Options.UserRoles.Member)
                return new Member(user);
            else if (userRole == Options.UserRoles.Admin)
                return new Admin(user);
            else
                return null;
        }
	}

}
